import ttkbootstrap as ttkb
from ttkbootstrap.constants import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.dates import DateFormatter, date2num
from datetime import datetime
import numpy as np
from tkinter import messagebox

# Windows 中文显示适配（与甘特图统一字体）
plt.rcParams.update({
    "font.family": ["Microsoft YaHei", "SimHei", "Arial"],
    "font.size": 9,
    "axes.facecolor": "#f8f9fa",
    "axes.grid": True,
    "grid.color": "#dee2e6",
    "grid.linewidth": 0.6,
    "xtick.direction": "in",
    "ytick.direction": "in",
    "figure.facecolor": "white",
    "figure.edgecolor": "none",
    "legend.fontsize": 8,
    "axes.unicode_minus": False
})

class StatPanel(ttkb.Frame):
    def __init__(self, parent):
        super().__init__(parent, padding=(10, 10))
        self.parent = parent  # 父容器（right_vertical_pane）
        self.tasks = []  # 任务数据（ID 为整数）
        self._build_ui()

    def _build_ui(self):
        """统计面板UI：双图布局（饼图+线图，Windows 尺寸适配）"""
        # 1. 标题栏
        self.title_frame = ttkb.Frame(self)
        self.title_frame.pack(fill=X, anchor=N, pady=(0, 8))
        self.title_label = ttkb.Label(self.title_frame, text="项目统计")
        self.title_label.pack(side=LEFT)
        
        self.divider = ttkb.Separator(self, orient=HORIZONTAL)
        self.divider.pack(fill=X, pady=(0, 8))
        
        # 2. 双图水平布局（左40%：饼图，右60%：线图）
        self.plot_container = ttkb.PanedWindow(self, orient=HORIZONTAL)
        self.plot_container.pack(fill=BOTH, expand=YES)
        
        # 左侧：任务状态饼图
        self.pie_frame = ttkb.Frame(self.plot_container)
        self.plot_container.add(self.pie_frame, weight=40)
        
        self.pie_fig, self.pie_ax = plt.subplots(figsize=(5, 4), dpi=100)  # Windows 分辨率
        self.pie_canvas = FigureCanvasTkAgg(self.pie_fig, master=self.pie_frame)
        self.pie_canvas.draw()
        self.pie_canvas.get_tk_widget().pack(fill=BOTH, expand=YES)
        
        # 右侧：进度趋势线图
        self.line_frame = ttkb.Frame(self.plot_container)
        self.plot_container.add(self.line_frame, weight=60)
        
        self.line_fig, self.line_ax = plt.subplots(figsize=(7, 4), dpi=100)  # Windows 分辨率
        self.line_canvas = FigureCanvasTkAgg(self.line_fig, master=self.line_frame)
        self.line_canvas.draw()
        self.line_canvas.get_tk_widget().pack(fill=BOTH, expand=YES)

    def update_stat(self, tasks):
        """更新统计图表（任务 ID 为整数）"""
        self.tasks = tasks
        if not self.tasks:
            self._draw_empty_pie()
            self._draw_empty_line()
            return
        
        # 绘制饼图和线图
        self._draw_status_pie()
        self._draw_progress_line()

    def _draw_empty_pie(self):
        """无任务时的饼图提示（中文适配）"""
        self.pie_ax.clear()
        self.pie_ax.text(
            0.5, 0.5, "暂无任务数据",
            ha="center", va="center", transform=self.pie_ax.transAxes,
            fontsize=11, color="#6c757d", fontfamily="Microsoft YaHei"
        )
        self.pie_ax.set_title("任务状态分布", fontsize=12, pad=15, fontfamily="Microsoft YaHei")
        self.pie_canvas.draw()

    def _draw_status_pie(self):
        """任务状态饼图（Windows 颜色适配）"""
        self.pie_ax.clear()
        
        # 统计状态数量（ID 为整数）
        status_count = {}
        for task in self.tasks:
            status = task[6]  # task[6] 是状态字段
            status_count[status] = status_count.get(status, 0) + 1
        
        # Windows 风格配色
        status_colors = {
            "未开始": "#6c757d",
            "进行中": "#007bff",
            "已完成": "#28a745",
            "延期": "#dc3545"
        }
        # 过滤无效状态
        labels = [s for s in status_count.keys() if s in status_colors]
        sizes = [status_count[s] for s in labels]
        colors = [status_colors[s] for s in labels]
        
        # 绘制饼图（带百分比，Windows 视觉风格）
        wedges, texts, autotexts = self.pie_ax.pie(
            sizes, labels=labels, colors=colors, autopct="%1.1f%%",
            startangle=90, shadow=True, explode=[0.05]*len(labels),
            textprops={"fontsize": 9, "fontfamily": "Microsoft YaHei"}
        )
        # 美化百分比文字（白色加粗）
        for autotext in autotexts:
            autotext.set_color("white")
            autotext.set_fontweight("bold")
        
        self.pie_ax.set_title("任务状态分布", fontsize=12, pad=15, fontfamily="Microsoft YaHei")
        self.pie_canvas.draw()

    def _draw_empty_line(self):
        """无任务时的线图提示（中文适配）"""
        self.line_ax.clear()
        self.line_ax.text(
            0.5, 0.5, "暂无任务数据",
            ha="center", va="center", transform=self.line_ax.transAxes,
            fontsize=11, color="#6c757d", fontfamily="Microsoft YaHei"
        )
        self.line_ax.set_title("任务进度趋势（按计划结束日期）", fontsize=12, pad=15, fontfamily="Microsoft YaHei")
        self.line_canvas.draw()

    def _draw_progress_line(self):
        """进度趋势线图（Windows 日期格式适配）"""
        self.line_ax.clear()
        
        # 按结束日期
    def _draw_progress_line(self):
        """进度趋势线图（Windows 日期格式+中文适配）"""
        self.line_ax.clear()
        
        # 按计划结束日期分组，计算每日平均进度（ID 为整数）
        date_progress = {}
        for task in self.tasks:
            end_date_str = task[5]  # task[5] = 计划结束日期
            progress = task[7]      # task[7] = 完成进度（0-100）
            task_id = task[0]       # 任务ID（整数，用于错误提示）
            
            # 处理 Windows 日期格式（兼容 YYYY-MM-DD）
            try:
                end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
            except ValueError:
                messagebox.showwarning("日期错误", f"任务ID {task_id} 日期格式错误（需为 YYYY-MM-DD）", parent=self)
                continue
            
            date_key = end_date.strftime("%Y-%m-%d")
            # 累计进度和任务数（计算平均值）
            if date_key not in date_progress:
                date_progress[date_key] = {"total": 0, "count": 0}
            date_progress[date_key]["total"] += progress
            date_progress[date_key]["count"] += 1
        
        # 处理无有效日期数据的情况
        if not date_progress:
            self._draw_empty_line()
            return
        
        # 排序日期+计算平均进度
        sorted_dates = sorted(date_progress.keys())
        avg_progress = [
            date_progress[date]["total"] / date_progress[date]["count"] 
            for date in sorted_dates
        ]
        # 转换日期为 matplotlib 可识别格式
        plot_dates = [date2num(datetime.strptime(date, "%Y-%m-%d")) for date in sorted_dates]
        
        # 绘制趋势线（Windows 视觉风格：带标记+填充）
        self.line_ax.plot(
            plot_dates, avg_progress, marker="o", markersize=4,
            linewidth=2, color="#007bff", label="平均进度",
            markerfacecolor="#ffffff", markeredgecolor="#007bff", markeredgewidth=1.5
        )
        # 填充线下方区域（增强可读性）
        self.line_ax.fill_between(
            plot_dates, avg_progress, alpha=0.3, color="#007bff"
        )
        
        # 配置 X 轴（日期格式适配 Windows 显示）
        self.line_ax.xaxis.set_major_formatter(DateFormatter("%m-%d", fontfamily="Microsoft YaHei"))
        plt.setp(self.line_ax.xaxis.get_majorticklabels(), rotation=45, ha="right")
        
        # 配置 Y 轴（进度范围 0-100，留 5% 余量）
        self.line_ax.set_ylim(0, 105)
        self.line_ax.set_ylabel("平均进度（%）", fontsize=10, fontfamily="Microsoft YaHei")
        
        # 网格和图例（Windows 风格）
        self.line_ax.grid(True, alpha=0.7, linestyle="-", linewidth=0.6)
        self.line_ax.legend(loc="lower right", fontfamily="Microsoft YaHei")
        
        # 标题（中文适配）
        self.line_ax.set_title("任务进度趋势（按计划结束日期）", fontsize=12, pad=15, fontfamily="Microsoft YaHei")
        plt.tight_layout()
        self.line_canvas.draw()
